import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'

const request = axios.create({
  baseURL: '/api',
  timeout: 5000,
})
// 请求拦截器
request.interceptors.request.use(
  //成功回调
  (config) => {
    const UserStore = useUserStore()
    if (UserStore.UserInfo.token) {
      // // 添加token,前端获取token带给后端
      // config.headers.Authorization = 'Bearer ${UserStore.UserInfo.token}'
      config.headers.Authorization = UserStore.UserInfo.token
    }

    return config
  },
  //失败回调
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截器
request.interceptors.response.use(
  //成功回调
  (response) => {
    return response.data
  },
  //失败回调
  (error) => {
    let message = ''
    let status = error.response?.status
    switch (status) {
      case 401:
        message = 'token过期'
        break
      case 403:
        message = '无权访问'
        break
      case 404:
        message = '请求错误'
        break
      case 500:
        message = '服务器错误'
        break
      default:
        message = '网络错误'
        break
    }
    ElMessage({
      type: 'error',
      message,
    })
    //判断超时重新请求
    const config = error.config
    if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
      return request(config) //重新请求
    }
    return Promise.reject(error)
  }
)
export default request
